package com.sleepcamel.exporter.util

import groovy.beans.Bindable

import java.sql.*

import com.sleepcamel.rest.domain.BaseBean;

/** Utility class for working with low-level JDBC connections and ResultSets. */

class JdbcUtils extends BaseBean{
        @Bindable String url = ""
        @Bindable String driver
        @Bindable String userName = ""
        @Bindable String password = ""
        Connection connection
        
        def executeScript(String sql) {
                execute {Connection con ->
                        Statement statement = con.createStatement();
                        try {
                                statement.execute(sql);
                        } finally {
                                statement?.close();
                        }
                }
        }
        
        def execute(Closure callme) {
                Class.forName(driver)
                try {
                        connection = DriverManager.getConnection (url,userName,password)
                        callme(connection)
                } finally {
                        connection?.close()
                        connection=null
                }
        }
        
        def iterate(ResultSet resultSet, Closure callme) {
                try {
                        while (resultSet.next()) {
                                callme(resultSet)
                        }
                } finally {
                        resultSet?.close()
                }
                
        }
}